import Axios from "@/api";

let userInfo: any = sessionStorage.getItem("userInfo");
userInfo = userInfo ? JSON.parse(userInfo) : null;

const state = {
  // 当前登录用户信息
  currentUser: userInfo ? userInfo.user : {},
  // 用户角色
  roles: userInfo ? userInfo.roles : [],
  // 用户权限
  permissions: userInfo ? userInfo.permissions : []
};

const mutations = {
  setUser(state: any, val: Api.UserInfoRes) {
    state.currentUser = val.user;
    state.roles = val.roles;
    state.permissions = val.permissions;
  }
};

const actions = {
  setUser({ commit }: any, val: Api.UserInfoRes) {
    commit("setUser", val);
  },

  /**
   * 更新本地用户信息
   * @param commit
   * @param force {Bollean} 是否强制更新本地session用户信息
   */
  async updateUser({ commit }: any, force = false) {
    const userInfo: any = sessionStorage.getItem("userInfo");
    const token = localStorage.getItem("token");

    if (token && (!userInfo || force)) {
      await Axios.GetInfo().then((res: any) => {
        if (res && res.code === 200) {
          const _data = { user: res.user, permissions: res.permissions, roles: res.roles };
          commit("setUser", _data);
          sessionStorage.setItem("userInfo", JSON.stringify(_data));
        }
      });
    }
    return Promise.resolve();
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
